package com.bit.book.interceptor;

import com.bit.book.constant.Constants;
import com.bit.book.model.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("登录拦截器进行拦截校验...");
        //判断用户是否登录
        HttpSession session = request.getSession(false);
        if (session==null || !StringUtils.hasLength((String)session.getAttribute(Constants.SESSION_LOGIN_USER_NAME))){
            //用户未登录
            response.setStatus(401);  //http状态码, 非业务码
            response.setContentType("text/html;charset=utf-8");
            response.getOutputStream().write("用户未登录".getBytes(StandardCharsets.UTF_8));

            //如果返回json
//            response.setContentType("application/json;charset=utf-8");
//            Result result = Result.unlogin();
//            response.getOutputStream().print();
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("目标方法执行后...");
    }

//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("视图渲染之后执行....");
//    }
}
